﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

#if TESTS

using System;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;


namespace Amarok.Agents
{
	[TestFixture]
	public class Test_OperationHandler
	{
		private class MyOperation : Operation<String, Int32>
		{
		}

		private MyOperation CallbackMessage;
		private Int32 CallbackCalled;
		private Boolean ThrowExceptionBeforeAwait;
		private Boolean ThrowExceptionAfterAwait;
		private Boolean ThrowCancellationException;

		private async Task<String> AsyncHandler(MyOperation operation)
		{
			CallbackMessage = operation;
			CallbackCalled++;

			if (ThrowExceptionBeforeAwait)
				throw new ApplicationException("BEFORE");

			await Task.Factory.StartNew(() => Thread.Sleep(250));

			if (ThrowExceptionAfterAwait)
				throw new ApplicationException("AFTER");

			return "done";
		}

		private async Task<String> CancellingAsyncHandler(MyOperation operation)
		{
			// simulate cancellation from other thread
			operation.Cancel();

			CallbackMessage = operation;
			CallbackCalled++;

			await Task.Factory.StartNew(() => Thread.Sleep(250));

			// throw cancellation exception
			if (ThrowCancellationException)
				operation.CancellationToken.ThrowIfCancellationRequested();

			return "done";
		}

		[SetUp]
		public void Setup()
		{
			CallbackMessage = null;
			CallbackCalled = 0;
			ThrowExceptionBeforeAwait = false;
			ThrowExceptionAfterAwait = false;
			ThrowCancellationException = false;
		}


		// --- TESTS ---


		[Test]
		public void Test_Invoke_Success()
		{
			MyOperation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Func<MyOperation, String>(msg =>
				{
					callbackMessage = msg;
					callbackCalled++;
					return "done";
				});

			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.SameAs(callback));
			Assert.That(handler.AsyncCallback, Is.Null);

			handlerInterface.Invoke(operation);

			Assert.That(callbackCalled, Is.EqualTo(1));
			Assert.That(callbackMessage, Is.SameAs(operation));

			Assert.That(operation.Completion.Wait(5000), Is.True);
			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.False);
			Assert.That(result.Result, Is.EqualTo("done"));
		}

		[Test]
		public void Test_Invoke_Async_Success()
		{
			var callback = new Func<MyOperation, Task<String>>(AsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);

			Assert.That(operation.Completion.Wait(5000), Is.True);
			var result = operation.Completion;

			Assert.That(CallbackCalled, Is.EqualTo(1));
			Assert.That(CallbackMessage, Is.SameAs(operation));

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.False);
			Assert.That(result.Result, Is.EqualTo("done"));
		}


		[Test]
		public void Test_Invoke_Exception()
		{
			MyOperation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Func<MyOperation, String>(msg =>
				{
					callbackMessage = msg;
					callbackCalled++;
					throw new ApplicationException("TEST");
				});

			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.SameAs(callback));
			Assert.That(handler.AsyncCallback, Is.Null);

			handlerInterface.Invoke(operation);

			Assert.That(callbackCalled, Is.EqualTo(1));
			Assert.That(callbackMessage, Is.SameAs(operation));

			Assert.Throws<AggregateException>(() =>
				operation.Completion.Wait(5000));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.True);
			Assert.That(result.Exception, Is.TypeOf<AggregateException>());
			Assert.That(result.Exception.InnerException, Is.TypeOf<ApplicationException>());
			Assert.That(result.Exception.InnerException.Message, Is.EqualTo("TEST"));
		}

		[Test]
		public void Test_Invoke_Async_Exception_BeforeAwait()
		{
			ThrowExceptionBeforeAwait = true;

			var callback = new Func<MyOperation, Task<String>>(AsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);
			operation.Completion.WaitQuietly();

			Assert.That(CallbackCalled, Is.EqualTo(1));
			Assert.That(CallbackMessage, Is.SameAs(operation));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.True);
			Assert.That(result.Exception, Is.TypeOf<AggregateException>());
			Assert.That(result.Exception.InnerException, Is.TypeOf<ApplicationException>());
			Assert.That(result.Exception.InnerException.Message, Is.EqualTo("BEFORE"));
		}

		[Test]
		public void Test_Invoke_Async_Exception_AfterAwait()
		{
			ThrowExceptionAfterAwait = true;

			var callback = new Func<MyOperation, Task<String>>(AsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);
			operation.Completion.WaitQuietly();

			Assert.That(CallbackCalled, Is.EqualTo(1));
			Assert.That(CallbackMessage, Is.SameAs(operation));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.True);
			Assert.That(result.Exception, Is.TypeOf<AggregateException>());
			Assert.That(result.Exception.InnerException, Is.TypeOf<ApplicationException>());
			Assert.That(result.Exception.InnerException.Message, Is.EqualTo("AFTER"));
		}


		[Test]
		public void Test_Invoke_Canceled_Before_Execution()
		{
			MyOperation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Func<MyOperation, String>(msg =>
				{
					callbackMessage = msg;
					callbackCalled++;
					return "done";
				});

			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.SameAs(callback));

			operation.Cancel();
			handlerInterface.Invoke(operation);

			Assert.That(callbackCalled, Is.EqualTo(0));
			Assert.That(callbackMessage, Is.Null);

			Assert.Throws<AggregateException>(() =>
				operation.Completion.Wait(5000));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.True);
			Assert.That(result.IsFaulted, Is.False);
		}

		[Test]
		public void Test_Invoke_Async_Canceled_Before_Execution()
		{
			var callback = new Func<MyOperation, Task<String>>(AsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			operation.Cancel();
			handlerInterface.Invoke(operation);
			operation.Completion.WaitQuietly();

			Assert.That(CallbackCalled, Is.EqualTo(0));
			Assert.That(CallbackMessage, Is.Null);

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.True);
			Assert.That(result.IsFaulted, Is.False);
		}


		[Test]
		public void Test_Invoke_Canceled_During_Execution()
		{
			MyOperation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Func<MyOperation, String>(msg =>
				{
					// simulate cancellation from other thread
					msg.Cancel();

					callbackMessage = msg;
					callbackCalled++;
					msg.CancellationToken.ThrowIfCancellationRequested();
					return "done";
				});

			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);

			Assert.That(callbackCalled, Is.EqualTo(1));
			Assert.That(callbackMessage, Is.SameAs(operation));

			Assert.Throws<AggregateException>(() =>
				operation.Completion.Wait(5000));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.True);
			Assert.That(result.IsFaulted, Is.False);
		}

		[Test]
		public void Test_Invoke_Async_Canceled_During_Execution()
		{
			ThrowCancellationException = true;

			var callback = new Func<MyOperation, Task<String>>(CancellingAsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);
			operation.Completion.WaitQuietly();

			Assert.That(CallbackCalled, Is.EqualTo(1));
			Assert.That(CallbackMessage, Is.SameAs(operation));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.True);
			Assert.That(result.IsFaulted, Is.False);
		}

		[Test]
		public void Test_Invoke_Canceled_During_Execution_CancellationIgnoredByHandler()
		{
			MyOperation callbackMessage = null;
			Int32 callbackCalled = 0;

			var callback = new Func<MyOperation, String>(msg =>
				{
					// simulate cancellation from other thread
					msg.Cancel();

					callbackMessage = msg;
					callbackCalled++;
					return "done";
				});

			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);

			Assert.That(callbackCalled, Is.EqualTo(1));
			Assert.That(callbackMessage, Is.SameAs(operation));

			Assert.That(operation.Completion.Wait(5000), Is.True);
			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.False);
			Assert.That(result.Result, Is.EqualTo("done"));
		}

		[Test]
		public void Test_Invoke_Async_Canceled_During_Execution_CancellationIgnoredByHandler()
		{
			ThrowCancellationException = false;

			var callback = new Func<MyOperation, Task<String>>(CancellingAsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			handlerInterface.Invoke(operation);
			operation.Completion.WaitQuietly();

			Assert.That(CallbackCalled, Is.EqualTo(1));
			Assert.That(CallbackMessage, Is.SameAs(operation));

			var result = operation.Completion;

			Assert.That(result, Is.Not.Null);
			Assert.That(result.IsCompleted, Is.True);
			Assert.That(result.IsCanceled, Is.False);
			Assert.That(result.IsFaulted, Is.False);
			Assert.That(result.Result, Is.EqualTo("done"));
		}


		[Test]
		public void Test_Invoke_Already_Acquired()
		{
			Int32 callbackCalled = 0;

			var callback = new Func<MyOperation, String>(msg =>
				{
					callbackCalled++;
					return "done";
				});

			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.SameAs(callback));
			Assert.That(handler.AsyncCallback, Is.Null);

			operation.Acquire();
			handlerInterface.Invoke(operation);

			Assert.That(callbackCalled, Is.EqualTo(0));
		}

		[Test]
		public void Test_Invoke_Async_Already_Acquired()
		{
			var callback = new Func<MyOperation, Task<String>>(AsyncHandler);
			var handler = new OperationHandler<MyOperation, String, Int32>(callback);
			var handlerInterface = (IHandler)handler;
			var operation = new MyOperation();

			Assert.That(handler.Callback, Is.Null);
			Assert.That(handler.AsyncCallback, Is.SameAs(callback));

			operation.Acquire();
			handlerInterface.Invoke(operation);

			Assert.That(CallbackCalled, Is.EqualTo(0));
		}

	}
}

#endif
